package models

import (
	"github.com/jinzhu/gorm"
	"time"
)

type Product struct {
	Model
	Name   string  `json:"name"`
	Type   int     `json:"type"`
	Spec   string  `json:"spec"`
	Price  float64 `json:"price"`
	ImgUrl string  `json:"img_url"`
	Remark string  `json:"remark"`
	Status int     `json:"status"`
}

func (product *Product) BeforeCreate(scope *gorm.Scope) error {
	scope.SetColumn("CreateTime", time.Now().Unix())
	scope.SetColumn("UpdateTime", time.Now().Unix())
	return nil
}

//修改时自动执行
func (product *Product) BeforeUpdate(scope *gorm.Scope) error {
	scope.SetColumn("UpdateTime", time.Now().Unix())
	return nil
}

func ExistProductById(id int) bool {
	var product Product
	db.Where("id=?", id).First(&product)
	if product.ID > 0 {
		return true
	}
	return false
}

func ExistProductByName(name string) bool {
	var product Product
	db.Where("name=?", name).First(&product)
	if product.ID > 0 {
		return true
	}
	return false
}

func GetProductTotal(maps interface{}) (count int) {
	db.Model(&Product{}).Where(maps).Where("status=?", 1).Count(&count)
	return
}

func GetProductById(id int) (*Product, error) {
	var product Product
	err := db.Where("id=?", id).First(&product).Error
	if err != nil {
		return nil, err
	}
	return &product, nil
}

func GetProductList(pageNum int, pageSize int, maps interface{}) (product []Product) {
	db.Where(maps).Where("status=?", 1).Offset(pageNum).Limit(pageSize).Find(&product)
	return
}

func AddProduct(data map[string]interface{}) bool {
	db.Create(&Product{
		Name:   data["name"].(string),
		Type:   data["type"].(int),
		Spec:   data["spec"].(string),
		Price:  data["price"].(float64),
		ImgUrl: data["imgUrl"].(string),
		Status: data["status"].(int),
		Remark: data["remark"].(string),
	})

	return true
}

func EditProduct(id int, data map[string]interface{}) bool {
	db.Model(&Product{}).Where("id=?", id).
		Update(&Product{
			Name:   data["name"].(string),
			Type:   data["type"].(int),
			Spec:   data["spec"].(string),
			Price:  data["price"].(float64),
			ImgUrl: data["imgUrl"].(string),
			Status: data["status"].(int),
			Remark: data["remark"].(string),
		})

	return true
}

func DelProduct(id int) bool {
	db.Model(&Product{}).Where("id=?", id).Update("status", 0)
	return true
}
